package src.E_Thread;

import java.util.concurrent.locks.ReentrantLock;

// 不安全线程，示例二（取钱）
public class E15_UnsafeThread02 {
    public static void main(String[] args) throws InterruptedException {
        Account account = new Account("环球基金", 1000,new ReentrantLock());
        Bank lele = new Bank(account,800,"乐乐");
        Bank mengmeng = new Bank(account,600,"梦梦");
        lele.start();
        mengmeng.start();
    }
}

class Bank extends Thread{
    private Account account; // 账户
    private int nowSum; // 要取的金额
    private int cash; // 手上现金

    public Bank(Account account, int nowSum, String name) {
        super(name);
        this.account = account;
        this.nowSum = nowSum;
    }

    // 定义lock锁，因为Bank类被new多次，所以锁就放account类了，然后传过来，保证一把锁锁的是同一个对象
    //private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        // 模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            account.lock.lock(); // 加锁了，现在安全了
            // 判断余额
            if (account.remainingSum < nowSum) {
                System.out.println(Thread.currentThread().getName() + " 钱被对象取走啦！");
                return;
            }
            // 模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 取钱
            account.remainingSum = account.remainingSum - nowSum;
            cash = cash + nowSum;
            System.out.println(this.getName() + " " + account.account + " 还剩：" + account.remainingSum + "w");
            System.out.println(this.getName() + " 现金有 " + cash + "w");
        }finally {
            account.lock.unlock(); // 释放锁
        }
    }
}

class Account{
    String account;
    int remainingSum;
    ReentrantLock lock;

    public Account(String account, int remainingSum, ReentrantLock lock) {
        this.account = account;
        this.remainingSum = remainingSum;
        this.lock = lock;
    }
}